package com.sgb.member.view_model;

import android.text.TextUtils;

import com.sgb.member.PickCateType;
import com.sgb.member.di.repository.MemberRepertory;
import com.sgb.member.entity.ListMResponse;
import com.sgb.member.entity.MemberBean;
import com.sgb.member.entity.MemberPersonBean;
import com.sgb.member.ui.activity.MemberRelieveActivity;
import com.sgb.member.ui.activity.MemberTransferActivity;
import com.sgb.member.ui.fragment.MemberTypeDemandFragment;
import com.sgb.member.weight.MemberCommonDialog;
import com.swgk.core.base.BaseViewModel;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.util.StringUtil;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.selection.CommonPopEntity;
import com.swgk.core.view.selection.CopyUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;

public class MemberTypeDemandModel extends BaseViewModel {

    private final MemberTypeDemandFragment fragment;
    private MemberRepertory repertory;

    private int current;
    private CommonPopEntity mAll;

    public MemberTypeDemandModel(MemberTypeDemandFragment fragment, MemberRepertory repertory) {
        this.fragment = fragment;
        this.repertory = repertory;

        mAll = new CommonPopEntity();
        mAll.setNo("");
        mAll.setTypeName("全部");
    }

    // 获取审批流程状态 approveType: applyJoinCompany/
    // 申請加盟审批类型 inviteJoinCompany

    /**
     * 获取审批流程状态
     *
     * @param approveType 邀请加盟审批类型 inviteJoinCompany
     *                    申請加盟审批类型 applyJoinCompany
     *                    会员企业调级 memberEvaluate
     *                    会员解除申请 memberRelieve
     *                    type 0 需方会员 1供方会员
     */
    public void getProcessStatus(int pos, String approveType, MemberBean bean) {
        DialogHelper.showProgressDialog(fragment.getActivity(), null, "数据获取中...", 0, false, null).setCanceledOnTouchOutside(false);
        String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        repertory.getApi().getProcessStatus(companyNo, approveType).enqueue(new ICallBack<BaseEntity<Object>>() {
            @Override
            public void onSuccess(BaseEntity<Object> data) {
                // "status": "1" //1 表示有审批 0 代表无审批
                String status = ((Map<String, String>) data.getData()).get("status");
                if (!TextUtils.isEmpty(status)) {
                    switch (approveType) {
                        case "memberEvaluate":
                            // 有审批显示弹窗, 跳转至会员调级申请页
                            if ("1".equals(status)) {
                                MemberCommonDialog dialog = new MemberCommonDialog(new MemberCommonDialog.SimpleListener() {
                                    @Override
                                    public void onPositive(Object... objects) {
                                        MemberTransferActivity.start(fragment.getContext(), bean, pos);
                                    }
                                }, MemberCommonDialog.STYLE_LEVEL);
                                dialog.show(fragment.getContext(), "MemberCommonDialog");
                                return;
                            } else {
                                // 无审批跳转至会员调级申请页
                                MemberTransferActivity.start(fragment.getContext(), bean, pos);
                            }
                            break;
                        case "memberRelieve":
                            // 无审批时弹出确认弹窗,
//                            MemberCommonDialog dialog;
//                            if ("0".equals(status)) {
//                                dialog = new MemberCommonDialog(new MemberCommonDialog.SimpleListener() {
//                                    @Override
//                                    public void onPositive(Object... objects) {
//                                        // 会员解除申请接口
//                                        relieveMember(pos, bean);
//                                    }
//                                }, MemberCommonDialog.STYLE_DISSOLUTION);
//                            } else {
                                // 有审批时跳转至会员解除申请页
//                                dialog = new MemberCommonDialog(new MemberCommonDialog.SimpleListener() {
//                                    @Override
//                                    public void onPositive(Object... objects) {
                                        MemberRelieveActivity.start(fragment.getContext(), bean, pos,status);
//                                    }
//                                }, MemberCommonDialog.STYLE_DISSOLUTION_APPLY);
//                            }
//                            dialog.show(fragment.getContext(), "MemberCommonDialog");
                            break;
                    }
                } else {
                    MToast.showToast(fragment.getContext(), "网络异常，请稍后重试");
                }
            }
        });
    }

    // 更新会员类型
    public void updateMemberType(int curPage, MemberBean bean, List<CommonPopEntity> types) {
        DialogHelper.showProgressDialog(fragment.getActivity(), "数据获取中...").setCanceledOnTouchOutside(false);
        Map<String, Object> map = new HashMap<>();
        map.put("no", bean.getNo());
        Map<String, List<CommonPopEntity>> typeMap = CopyUtils.memberTypeToJson(types);
        map.put("firstCategory", getNos(typeMap.get("firstCategory")));
        map.put("secondCategory", getNos(typeMap.get("secondCategory")));
        map.put("thirdCategory", getNos(typeMap.get("thirdCategory")));
        map.put("fourCategory", getNos(typeMap.get("fourCategory")));
        map.put("fiveCategory", getNos(typeMap.get("fiveCategory")));
        map.put("inviType", curPage == 0 ? "2" : "1");  //申请类型 供方会员1 上游会员 2
        repertory.getApi().updateMemberType(map).enqueue(new ICallBack<BaseEntity<BaseEntity>>() {
            @Override
            public void onSuccess(BaseEntity<BaseEntity> data) {
                List<String> strings = new ArrayList<>();
                for (CommonPopEntity type : types) {
                    strings.add(type.getTypeName());
                }
                bean.setAllCategoryName(strings);
                fragment.updateMemberType(bean);
            }
        });
    }

    private List<String> getNos(List<CommonPopEntity> list) {
        List<String> strings = new ArrayList<>();
        if (list == null || list.size() == 0) {
            return strings;
        }
        for (CommonPopEntity popEntity : list) {
            strings.add(popEntity.getNo());
        }
        return strings;
    }

    // 解除会员申请
    public void relieveMember(int pos, MemberBean bean) {
        DialogHelper.showProgressDialog(fragment.getActivity(), null, "数据获取中...", 0, false, null).setCanceledOnTouchOutside(false);
        repertory.getApi().relieveMember(bean.getNo()).enqueue(new ICallBack<BaseEntity<BaseEntity>>() {
            @Override
            public void onSuccess(BaseEntity<BaseEntity> data) {
                MToast.showToast(fragment.getContext(), "解除会员成功");
                fragment.removeMember(pos, bean);
            }
        });
    }

    public void userFocus(String businessNo, boolean isGz, int position) {
        Map<String, Object> map = new HashMap<>();
        map.put("businessNo", businessNo);
        map.put("type", 0); // 固定值0
        DialogHelper.showProgressDialog(fragment.getContext(), null, "请求中...", 0, false, null).setCanceledOnTouchOutside(false);
        repertory.getApi().userFocus(map).enqueue(new ICallBack<BaseEntity>() {
            @Override
            public void onSuccess(BaseEntity data) {
                fragment.updateMemberFollow(isGz, position);
            }
        });
    }

    // checkType 会员主体 "1", "企业会员"
    //                   "0", "个人会员"
    public void getMyMembers(boolean isLoadMore, String companyName, String checkType, String mNo0, String mNo1, String mNo2, String mNo3, String mNo4, String mNo41, String mNo5, String mNo6, String mNo7, String mNo8, String mNo9, String mNo10) {
        int currentPage = isLoadMore ? current + 1 : 1;
        DialogHelper.showProgressDialog(fragment.getActivity(), null, "数据获取中...", 0, false, null).setCanceledOnTouchOutside(false);
        Map<String, Object> map = new HashMap<>();
        map.put("companyName", companyName); //搜索企业名称
        map.put("memberType", StringUtil.isEmpty(mNo1) ? mNo0 : mNo1); //会员类型
        map.put("companyType", mNo2); //企业类型
        map.put("level", mNo3); //企业等级
        map.put("provinceNo", mNo4); //经营地址 省【add】
        map.put("cityNo", mNo41); //经营地址 市【add】
        map.put("qualificationType", mNo5); //资质类型【add】
        map.put("honourType", mNo6); //荣誉分类【add】
        map.put("assetCategories", mNo7);//固定资产分类【add】
        map.put("knowledgeType", mNo8); //知识产权分类【add】
        map.put("moneyType", mNo9); //单次金额最大【add】
        map.put("isHaveZc", mNo10); //是否有招采信息【add】
        map.put("relation", "1"); // 会员关系 1供方 2需方
        map.put("limit", 20);
        map.put("page", currentPage);
        Call<BaseEntity<ListMResponse<List<MemberBean>>>> call;
        if ("1".equals(checkType)) {
            call = repertory.getApi().getMembers(map);
        } else {
            getPersonMemberData(isLoadMore, map);
            return;
        }
        call.enqueue(new ICallBack<BaseEntity<ListMResponse<List<MemberBean>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListMResponse<List<MemberBean>>> data) {
                current = data.getData().getCurrent();
                int total = data.getData().getPages();
                fragment.refreshRecycler(data.getData().getList(), isLoadMore, current >= total);
            }

            @Override
            public void onFailure(Call<BaseEntity<ListMResponse<List<MemberBean>>>> call, Throwable t) {
                super.onFailure(call, t);
                if(!isLoadMore){
                    fragment.showEmpty();
                }
            }
        });
    }

    // checkType 会员主体 "1", "企业会员"
    //                   "0", "个人会员"
    public void getJoinMembers(boolean isLoadMore, String companyName, String checkType, String mNo0, String mNo1, String mNo2, String mNo3, String mNo4, String mNo41, String mNo5, String mNo6, String mNo7, String mNo8, String mNo9, String mNo10) {
        int currentPage = isLoadMore ? current + 1 : 1;
        DialogHelper.showProgressDialog(fragment.getActivity(), null, "数据获取中...", 0, false, null).setCanceledOnTouchOutside(false);
        Map<String, Object> map = new HashMap<>();
        map.put("companyName", companyName); //搜索企业名称
        map.put("memberType", StringUtil.isEmpty(mNo1) ? mNo0 : mNo1); //会员类型
        map.put("companyType", mNo2); //企业类型
        map.put("level", mNo3); //企业等级
        map.put("provinceNo", mNo4); //经营地址 省【add】
        map.put("cityNo", mNo41); //经营地址 市【add】
        map.put("qualificationType", mNo5); //资质类型【add】
        map.put("honourType", mNo6); //荣誉分类【add】
        map.put("assetCategories", mNo7);//固定资产分类【add】
        map.put("knowledgeType", mNo8); //知识产权分类【add】
        map.put("moneyType", mNo9); //单次金额最大【add】
        map.put("isHaveZc", mNo10); //是否有招采信息【add】
        map.put("relation", "2"); // 会员关系 1供方 2需方
        map.put("limit", 20);
        map.put("page", currentPage);
        Call<BaseEntity<ListMResponse<List<MemberBean>>>> call;
        if ("1".equals(checkType)) {
            call = repertory.getApi().getJoinMembers(map);
        } else {
            getPersonMemberData(isLoadMore, map);
            return;
        }
        call.enqueue(new ICallBack<BaseEntity<ListMResponse<List<MemberBean>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListMResponse<List<MemberBean>>> data) {
                current = data.getData().getCurrent();
                int total = data.getData().getPages();
                fragment.refreshRecycler(data.getData().getList(), isLoadMore, current >= total);
            }

            @Override
            public void onFailure(Call<BaseEntity<ListMResponse<List<MemberBean>>>> call, Throwable t) {
                super.onFailure(call, t);
                if(!isLoadMore){
                    fragment.showEmpty();
                }
            }
        });
    }

    private void getPersonMemberData(boolean isLoadMore, Map<String, Object> map) {
        repertory.getApi().getMemberLeaguePersonList(map).enqueue(new ICallBack<BaseEntity<ListMResponse<List<MemberPersonBean>>>>() {
            @Override
            public void onSuccess(BaseEntity<ListMResponse<List<MemberPersonBean>>> data) {
                current = data.getData().getCurrent();
                int total = data.getData().getPages();
                fragment.refreshRecycler(data.getData().getList(), isLoadMore, current >= total);
            }

            @Override
            public void onFailure(Call<BaseEntity<ListMResponse<List<MemberPersonBean>>>> call, Throwable t) {
                super.onFailure(call, t);
                if(!isLoadMore){
                    fragment.showEmpty();
                }
            }
        });
    }

    public void getLeftChooseData(int type, boolean isShowLeftDialog, boolean isDemandMember, String no) {
        Call<BaseEntity<List<CommonPopEntity>>> call = null;
        switch (type) {
            case PickCateType.TYPE_0:
                // 会员主体
                List<CommonPopEntity> listMain = new ArrayList<>();
                listMain.add(new CommonPopEntity("1", "企业会员"));
                listMain.add(new CommonPopEntity("0", "个人会员"));
                if (isShowLeftDialog) {
                    fragment.showLeftChooseDialog(type, listMain);
                } else {
                    fragment.setLeftChooseData(type, listMain);
                }
                break;
            case PickCateType.TYPE_01:
                // 会员类型 0 供方 1需方
                String ascription = isDemandMember ? "1" : "0";
                call = repertory.getApi().getMemberTypeList(ascription);
                break;
            case PickCateType.TYPE_1:
                // 会员类型二级
                call = repertory.getApi().getMemberTypeSubList(no);
                break;
            case PickCateType.TYPE_2:
                // 企业类型
                call = repertory.getApi().getCompanyTypeList();
                break;
            case PickCateType.TYPE_3:
                // 会员等级
                call = repertory.getApi().getMemberLevelList();
                break;
            case PickCateType.TYPE_4:
                // 资质类型
                call = repertory.getApi().getQualifyTypeTreeList();
                break;
            case PickCateType.TYPE_5:
                break;
            case PickCateType.TYPE_6:
                // 荣誉分类
                call = repertory.getApi().getHonorTypeList();
                break;
            case PickCateType.TYPE_7:
                // 固定资产
                call = repertory.getApi().getAssetType();
                break;
            case PickCateType.TYPE_8:
                // 知识产权
                call = repertory.getApi().getmemberIntellectualPropertyRightType();
                break;
            case PickCateType.TYPE_9:
                // 单次业绩最大金额
                call = repertory.getApi().performanceAmountList();
                break;
            case PickCateType.TYPE_10:
                // 是否有招采信息，1有0没有
                List<CommonPopEntity> list = new ArrayList<>();
                list.add(mAll);
                list.add(new CommonPopEntity("1", "是"));
                list.add(new CommonPopEntity("0", "否"));
                if (isShowLeftDialog) {
                    fragment.showLeftChooseDialog(type, list);
                } else {
                    fragment.setLeftChooseData(type, list);
                }
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + type);
        }
        if (call == null) {
            DialogHelper.dismissProgressDialog();
            return;
        }
        call.enqueue(new ICallBack<BaseEntity<List<CommonPopEntity>>>() {
            @Override
            public void onSuccess(BaseEntity<List<CommonPopEntity>> data) {
                if (data.getData() != null && data.getData() != null) {
                    if (type == PickCateType.TYPE_01
                            || type == PickCateType.TYPE_1
                            || type == PickCateType.TYPE_2
                            || type == PickCateType.TYPE_4
                            || type == PickCateType.TYPE_6
                            || type == PickCateType.TYPE_7
                    ) {
                        data.getData().add(0, mAll);
                    }
                    if (isShowLeftDialog) {
                        fragment.showLeftChooseDialog(type, data.getData());
                    } else {
                        fragment.setLeftChooseData(type, data.getData());
                    }
                }else{
                    if (isShowLeftDialog) {
                        fragment.showLeftChooseDialog(type, new ArrayList<>());
                    } else {
                        fragment.setLeftChooseData(type, new ArrayList<>());
                    }
                }
            }
        });
    }

    /**
     * 获取省市区地址
     */
    public void getAddressModel() {
        DialogHelper.showProgressDialog(fragment.getActivity(), "数据加载中...");
        repertory.getApi().getAddressEntityCityList().enqueue(new ICallBack<BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>>>() {
            @Override
            public void onSuccess(BaseEntity<List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>>> data) {
                DialogHelper.dismissProgressDialog();
                if (data != null && data.getData() != null && data.getData().size() > 0) {
                    fragment.setAddressData(data.getData());
                }
            }
        });
    }

    /**
     * 修改会员调级
     *
     * @param pos   当前下标
     * @param no    业务no
     * @param lever 等级
     * @param type  类型:1企业 2个人
     */
    public void onMemberTransfer(int pos, String no, String lever, int type) {

    }

    public void onMemberDissolution(int pos, MemberPersonBean bean) {
        // 会员解除
    }

    public void onMemberModify(int pos, MemberPersonBean bean) {
        // 会员类型修改
    }
}
